package com.haoran.dwz.common.security;
import java.util.Collection;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;

import com.haoran.dwz.domain.entities.Role;
import com.haoran.dwz.domain.entities.User;

public class UsmContextHolder {
	
    public static User getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Assert.notNull(authentication,"用户鉴权信息应该不为空");
        Object principal = authentication.getPrincipal();
        if(principal != null &&  principal instanceof User) {
        	return  (User)principal;
        }
		return null;
    }
    
    /**
     * 获取用户ID
     * @return
     */
    public static String getUserId() {
    	User user = getUser();
    	Assert.notNull(user,"用户应该不为空");
    	return user.getId();
    }
    
    /**
     * 获取用户Email
     * @return
     */
    public static String getEmail() {
    	User user = getUser();
    	Assert.notNull(user,"用户应该不为空");
    	return user.getEmail();
    }
    
    @SuppressWarnings("unchecked")
	public static Collection<Role> getAuthorities() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        assert authentication != null;
        return (Collection<Role>) authentication.getAuthorities();
    }
}